package com.kantboot.project.util.common.service;

import com.kantboot.project.util.common.exception.UpdateException;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Id;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

@Service
public class BaseService<T,ID> {

    @Resource
    EntityManagerFactory entityManagerFactory;

    /**
     * 根据参数中的id删除
     * @param entity
     * @return 删除成功 或者 删除失败
     */
    public void remove(@RequestBody T entity){
        EntityManager entityManager=entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        SimpleJpaRepository<T,ID> jpaRepository=new SimpleJpaRepository<T, ID>((Class<T>) entity.getClass(),entityManager);
        transaction.begin();
        Object o = entityManager.find(entity.getClass(), getId(entity));
        try{
            jpaRepository.delete((T) o);
        }catch (Exception e){
            entityManager.close();
            throw new UpdateException().setMessage("删除失败");
        }
        transaction.commit();
        entityManager.close();
    }



    /**
     * 这个方法会将一段文本注入到某个类中添加了@Autowired注解的方法中，并将实例对象返回
     */
    public Object getId(Object object) {
        // 从Class对象中获取Demo中声明方法对应的Method对象
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            // 判断方法是否被加上了@Autowired这个注解
            if(field.isAnnotationPresent(Id.class)) {
                field.setAccessible(true);
                try {
                    return field.get(object);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 获得所有不为空的字段
     * @param source
     * @return
     */
    public String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

}